//
//  ViewController.swift
//  YSM
//
//  Created by ys on 2018/7/13.
//  Copyright © 2018年 ys. All rights reserved.
//

import UIKit

extension Notification.Name {
    public static let RLoginSucess = NSNotification.Name("RLoginSucess")
    public static let RLogout = NSNotification.Name("RLogout")
}


protocol YSRouterCommonProtocol:NSObjectProtocol {
    var removeTag: String { get set }
    func loadVCInfo(params:Any)
    func reciveRouterCommon(name:Notification.Name, params:Any?)
}

/// 公共类
class YSRouterCommon {
    
    private static let share = YSRouterCommon()
    
//    private var commObjcs:[BaseViewControllerProxy] = []
    
    private var commonDics: [String: BaseViewControllerProxy] = [:]
    
    /// 添加通知
    class public func addRouterCommon(names:Notification.Name..., target: YSRouterCommonProtocol) {
        print("添加通知\(names.description), target = \(target.description)")
        share.addCommon(names: names, target: target)
    }
    
    /// 推送通知
    class public func postRouterCommon(name:Notification.Name, params:Any? = nil, completion: ((_ finshed: Bool)->Void)? = nil) {
        share.postCommon(name: name, params: params, completion: completion)
    }
    
    /// 删除通知
    class public func romveRouterCommon(target: YSRouterCommonProtocol) {
        share.removeCommon(target: target)
    }
    
    private func addCommon(names:[Notification.Name], target: YSRouterCommonProtocol) {
        for (_, weakVc) in self.commonDics {
            if let vc = weakVc.vc {
                if (vc as! UIViewController) == (target as! UIViewController){
                    return
                }
            }
        }
        
        let weakVc = BaseViewControllerProxy(vc: target)
        weakVc.notifiArr.append(contentsOf: names)
        
        let key = "\(type(of:target))"
        self.commonDics[key] = weakVc
        
        // tag，方便删除
        target.removeTag = key
    }
    
    private func postCommon(name:Notification.Name, params:Any?, completion: ((_ finshed: Bool)->Void)?) {
        // 开子线程
        for (_, weakVc) in self.commonDics {
            if let vc = weakVc.vc {
                if weakVc.notifiArr.contains(name) {
                    vc.reciveRouterCommon(name: name, params: params)
                }
                
                print("reciveRouterCommon:\(vc)")
            }
        }
        if completion != nil {
            completion!(true)
        }
    }
    private func removeCommon(target: YSRouterCommonProtocol) {
        if target.removeTag != "" {
            self.commonDics.removeValue(forKey: target.removeTag)
        }
        
        print(self.commonDics)
    }
    
    private init() {
        
    }
}

class BaseViewControllerProxy: NSObject {
    
    weak var vc:YSRouterCommonProtocol?
    /// 收集的通知key
    var notifiArr:[Notification.Name] = []
    init(vc: YSRouterCommonProtocol) {
        self.vc = vc
        super.init()
    }
}
